package com.ht.api.handler;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import com.ht.api.bean.UserInfo;
import com.ht.api.db.exception.HtException;
import com.ht.api.util.UserUtil;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

/**
 * 获取登陆用户，保存到UserUtil对象中，方便在任何地方调用
 * @author asq
 * @createTime 2024年12月23日 10:02:09
 */
@Component
public class LoginUserHandler implements HandlerInterceptor {

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
		try {
			// 从token中获取用户信息
			UserInfo loginUser = UserUtil.getUserInfo(request);

			// 设置到ThreadLocal
			UserUtil.setLoginUser(loginUser);
			
			return true;
		} catch (Exception e) {
			throw new HtException("未登录或token已过期");
		}
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
			Exception ex) {
		// 请求完成后清除ThreadLocal，防止内存泄漏
		UserUtil.clear();
	}
}
